import { Link, useNavigate } from "react-router-dom";
import { Dropdown, Button } from "antd";
import type { ItemType } from "antd/lib/menu/hooks/useItems";
import "./index.less";

import { useSelector, useDispatch } from "react-redux";
import type { RootState, AppDispatch } from "@/store";
import { logoutAsync } from "@/pages/login/loginSlice";

function AvatarComponent() {
  const navigator = useNavigate();
  const dispatch = useDispatch<AppDispatch>();

  const handleLogout = async () => {
    await dispatch(logoutAsync());
    navigator("/login");
  };

  const items: ItemType[] = [
    { key: 0, label: <Link to="/syt/dashboard">返回首页</Link> },
    { key: 1, label: <div onClick={handleLogout}>退出登录</div> },
  ];

  const name = useSelector<RootState>((state) => state.login.name) as string;
  const avatar = useSelector<RootState>(
    (state) => state.login.avatar
  ) as string;

  return (
    <>
      <Dropdown menu={{ items }} trigger={["click"]}>
        <Button className="layout-dropdown-link" type="link">
          <span className="name">{name}</span>
          <img className="layout-avatar" src={avatar} alt="avatar" />
        </Button>
      </Dropdown>
    </>
  );
}

export default AvatarComponent;
